// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Avoid 'chrome' namespace
var isChrome = false; //On Chrome
if (typeof browser === "undefined" && typeof chrome === "object") {
	var browser = chrome; //On Chrome
	isChrome = true;
}

// Conditionally initialize the options.
browser.storage.local.get(null, function (result) {
	if (undefined == result["CopyFileNameIsInitialized"]) {
		browser.storage.local.set({ "CopyFileNameNoExtension": false });
		browser.storage.local.set({ "CopyFileNameIsInitialized": true });
	}
});

function getFileName(path) {
	var pos1 = path.lastIndexOf('/');
	var pos2 = path.lastIndexOf('\\');
	var pos = Math.max(pos1, pos2);
	if (pos < 0)
		return path;
	else
		return path.substring(pos + 1);
}

function getFileNameNoExt(path) {
	var pos1 = path.lastIndexOf('/');
	var pos2 = path.lastIndexOf('\\');
	var pos = Math.max(pos1, pos2);
	var filename;
	if (pos < 0)
		filename = path;
	else
		filename = path.substring(pos + 1);
	return filename.substring(0, filename.lastIndexOf('.'));
}

async function handleFileURL(info) {
	// now copy the file name to clipboard
	var result = await browser.storage.local.get('CopyFileNameNoExtension')
	var bNoExtension = JSON.parse(result['CopyFileNameNoExtension']);
	var copyText = "";
	if (info.mediaType == "image") {
		var ImageUrl = info.srcUrl;
		var ImageFileName;
		if (bNoExtension)
			ImageFileName = getFileNameNoExt(ImageUrl);
		else
			ImageFileName = getFileName(ImageUrl);
		copyText = ImageFileName;
	} else {
		var LinkUrl = info.linkUrl;
		var LinkFileName;
		if (bNoExtension)
			LinkFileName = getFileNameNoExt(LinkUrl);
		else
			LinkFileName = getFileName(LinkUrl);
		copyText = LinkFileName;
	}
	await browser.offscreen.createDocument({
		url: browser.runtime.getURL('copy.html'),
		reasons: ['CLIPBOARD'],
		justification: 'Required by Chrome to copy text.',
	});
	browser.runtime.sendMessage({ type: 'copy2clipboard', text: copyText }).catch((error) => {
		console.warn("Could not send message", error)
	})
}

/**
 * Create a context menu which will only show up for images.
 */
browser.contextMenus.create({
	id: "Copy-File-Name",
	title: "Copy File Name",
	type: 'normal',
	contexts: ["image", "link"]
});

browser.contextMenus.onClicked.addListener(function (info, tab) {
	handleFileURL(info);
});
